package arithmetic.socket;

import groovy.json.JsonOutput;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author jiangfeng 2019/7/17 22:37
 */
public class SocketServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(666);

        while (true){
            System.out.println("server将一直等待连接的到来");
            Socket accept = serverSocket.accept();
            InetAddress inetAddress = accept.getInetAddress();
            System.out.println("收到客户端连接："+ inetAddress.toString());

            InputStream inputStream = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len,"UTF-8"));
            }
            System.out.println("get message from client: " + sb);
            inputStream.close();
        }
    }



}
